package com.kevin.single;

import com.kevin.list.AbstractList;
import com.kevin.list.List;

/**
 * @Author LXL
 * @Date 2020/9/26 9:46
 **/
public class LinkedList1<E> extends AbstractList<E> implements List<E> {

    private Node<E> first;

    private static class Node<E> {
        private E elemet;
        private Node<E> next;

        public Node(E elemet,  Node<E> next){
            this.elemet = elemet;
            this.next = next;
        }
    }
    @Override
    public void clear() {
        size = 0;
        first = null;
    }

    @Override
    public E get(int index) {
        /**
         * 最好：O(1)
         * 最坏：O(N)
         * 平均：O(N)
         */
        return node(index).elemet;
    }

    @Override
    public E set(int index, E element) {
        /**
         * 最好：O(1)
         * 最坏：O(N)
         * 平均：O(N)
         */
        Node<E> node = node(index);
        E oldElment =  node.elemet;
        node.elemet = element;
        return oldElment;
    }

    @Override
    public void add(int index, E element) {
        /*
         * 最好：O(1)
         * 最坏：O(n)
         * 平均：O(n)
         */
        rangeCheckForAdd(index);
        if (index == 0){
            first = new Node<E>(element, first);
        }else {
            Node<E> prev = node(index - 1);
            prev.next = new Node<E>(element, prev.next);
        }
        size++;
    }

    @Override
    public E remove(int index) {
        rangeCheck(index);

        Node<E> node = first;
        if (index == 0){
            first = first.next;
        }else {
            Node<E> prev = node(index - 1);
            node = prev.next;
            prev.next = node.next;
        }
        size --;
        return node.elemet;
    }

    @Override
    public int indexOf(E element) {
        if (element == null){
            Node<E> node = first;
            for (int i = 0 ; i < size ; i++){
                if (node.elemet == null){
                    return i;
                }

                node = node.next;
            }
        }else {
            Node<E> node = first;
            for (int i = 0 ; i < size ; i++){
                if (element.equals(node.elemet)){
                    return i;
                }
                node = node.next;
            }
        }
        return ELEMENT_NOT_FOUND;
    }

    private Node<E> node(int index){
        rangeCheck(index);
        Node<E> node = first;
        for (int i = 0 ; i < index ; i++){
            node = node.next;
        }
        return node;
    }

    @Override
    public String toString() {
        StringBuilder string = new StringBuilder();
        string.append("size=").append(size).append(", [");
        Node<E> node = first;
        for (int i = 0; i < size; i++) {
            if (i != 0) {
                string.append(", ");
            }
            string.append(node.elemet);
            node = node.next;
        }
        string.append("]");
        return string.toString();
    }
}
